import { reqGetDeparmentList, reqGetScheduleList, reqGetScheduleRuleList } from "@/api/hospital/hospitalList";
import { Department, DepartmentList, Schedule, ScheduleList, ScheduleRuleList } from "@/api/hospital/hospitalList/types";
import { Button, Card, Col, Pagination, Row, Table, Tag, Tree, TreeDataNode, message } from "antd";
import { ColumnsType } from "antd/lib/table";
import {useState, useEffect} from 'react'
import { useParams } from "react-router-dom";

export default function HospitalSchedule() {




  // 部门树状列表
  const [departmentList, setDepartmentList] = useState<DepartmentList>([])

  // 得到路由的param参数 hoscode
  // const hoscode = useParams().hoscode as string
  /* 表达式!: 非空断言  断言左边的表达的值不是null/undefined */
  const hoscode = useParams().hoscode!

  // 初始化(利用useEffect)调用reqGetDeparmentList获取部门列表, 并更新状态显示
  useEffect(() => {
    async function getDepartmentList() {
      const list = await reqGetDeparmentList(hoscode)
      // 给所有的一级部门数据对象添加disabled为true属性
      setDepartmentList(list.map(item => ({...item, disabled: true})))
      // expandedKeys由所有一级部门的depcode组成的数组
      setExpandedKeys(list.map(item => item.depcode))
      // 得到部门列表后, 将第一个子部门的depcode设置为selectedKey
      if (list[0].children) {
        setSelectedKey(list[0].children[0].depcode)
        setDepname(list[0].children[0].depname)
      }
      // setSelectedKey(list[0].children![0].depcode)
      
    }
    getDepartmentList()
  }, [])


  // const treeData: TreeDataNode[] = [
  //   {
  //     title: 'parent 1-0',  // 显示的标题
  //     key: '0-0-0', // 标识
  //     disabled: true, // 是否禁用
  //     children: [ // 子节点的数组
  //       {
  //         title: 'leaf',
  //         key: '0-0-0-0',
  //       },
  //       {
  //         title: 'leaf',
  //         key: '0-0-0-1',
  //       },
  //     ],
  //   },
  //   {
  //     title: 'parent 1-1',
  //     key: '0-0-1',
  //     children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
  //   },
  // ];

  // - 定义一个所有需要展开的key的数组状态  expandedKeys
  const [expandedKeys, setExpandedKeys] = useState<string[]>([])
  // 定义一个选中节点的key值状态: selectedKey (某个部门的depcode)
  const [selectedKey, setSelectedKey] = useState('')



  // 排班规则分页列表相关数据
  const [scheduleRuleList, setScheduleRuleList] = useState<ScheduleRuleList>([])
  const [total, setTotal] = useState(53)
  const [current, setCUrrent] = useState(1)
  const [pageSize, setPageSize] = useState(5)

  //  - 定义医院名称的状态: hosname
  // - 定义当前科室的名称: depname
  // 工作日期: selectedWorkDate
  const [selectedWorkDate, setSelectedWorkDate] = useState('')
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')

  /* 
  定义获取分页列表数据并显示的函数: getScheduleRuleList (page, limit)
- 调用reqGetScheduleRuleList({})得到分页列表数据并更新状态
  */
  async function getScheduleRuleList (page: number, limit: number) {
    setCUrrent(page)
    setPageSize(limit)
    const {total, bookingScheduleList, baseMap:{hosname}} = await reqGetScheduleRuleList({ page, limit, hoscode, depcode: selectedKey })
    setScheduleRuleList(bookingScheduleList)
    setTotal(total)
    setHosname(hosname)
    
    if (total===0) {
      // 提示没有排班数据
      message.warn('没有排班数据')
      // 清理一些数据
      setSelectedWorkDate('')
      setScheduleList([])
    } else {
      // 将第一个规则对象的workDate指定为当前的
      setSelectedWorkDate(bookingScheduleList[0].workDate)
    }
    
  }

  // 监视selectedKey变化, 一旦变化了, 调用getScheduleRuleList
  useEffect(() => {
    if (selectedKey) { // 注意: 必须是有值才调用
      getScheduleRuleList(1, 5)
    }
    
  }, [selectedKey])




  // 排班列表
  const [scheduleList, setScheduleList] = useState<ScheduleList>([])
  // 排班列表的columns
  const columns: ColumnsType<Schedule> = [
    {
      title: '序号',
      render: (_, __, index) => index + 1,
      align: 'center',
      width: 80
    },
    {
      title: '姓名',
      dataIndex: 'docname'
    },

    {
      title: '职称',
      dataIndex: 'title'
    },

    {
      title: '号源时间',
      dataIndex: 'workDate'
    },

    {
      title: '总预约数',
      dataIndex: 'reservedNumber'
    },

    {
      title: '剩余预约数',
      dataIndex: 'availableNumber'
    },

    {
      title: '挂号费(元)',
      dataIndex: 'amount'
    },

    {
      title: '擅长技能',
      dataIndex: 'skill'
    }
   
  ];

  // 定义获取分页列表数据并显示的函数
  const getScheduleList = async () => {
    const list = await reqGetScheduleList({ workDate: selectedWorkDate, hoscode, depcode: selectedKey })
    setScheduleList(list)
  }

  // 监视selectedWorkDate的变化, 一旦变了调用
  useEffect(() => {
    if (selectedWorkDate) {
      getScheduleList()
    }
  }, [selectedWorkDate])



  // 容器div的高度计算:  页面高度 - 头部高度(64) -  导航的高度(44) -  Card的内边距(48) - 标题p的高度(36)
  const treeHeight = document.documentElement.clientHeight - 64 - 44 - 48 - 36


  return (
    <Card>
      <p>选择：{hosname} / {depname} / {selectedWorkDate}</p>
      <Row gutter={20}>
        <Col span={5}>
          <div 
            style={{
              height: treeHeight,
              overflowY: 'scroll'
            }}
          >
          <Tree
            treeData={departmentList as []}
            fieldNames={{key: 'depcode', title: 'depname'}}
            // defaultExpandAll
            expandedKeys={expandedKeys}
            selectedKeys={[selectedKey]}
            onSelect={(selectedKeys, info) => { // - - 当点击某个子部门项时, 将对应的depcode设置为selectedKey
              // 得到选择项的key
              const key = selectedKeys[0]
              setSelectedKey(key as string)

              // 得到对应的部门对象的depname
              const depname = (info.node as any).depname
              setDepname(depname)
            }}
          />
          </div>
          
        </Col>
        <Col span={19}>
          {
            scheduleRuleList.map(item => (
              <Tag key={item.workDate} 
                style={{marginBottom: 10}} 
                color={item.workDate===selectedWorkDate ? 'green' : ''}
                onClick={() => setSelectedWorkDate(item.workDate)}
              >
                <div>{item.workDate} {item.dayOfWeek}</div>
                <div>{item.availableNumber} / {item.reservedNumber}</div>
              </Tag>
            ))

          }

          <Pagination
            style={{marginTop: 20}}
            total={total}
            current={current}
            pageSize={pageSize}
            pageSizeOptions={[5, 10, 15]}
            // onChange={(page, pageSize) => getScheduleRuleList(page, pageSize)}
            onChange={getScheduleRuleList}
          />

          <Table
            style={{margin: '20px 0'}}
            dataSource={scheduleList}
            columns={columns}
          />

          <Button>返回</Button>
        </Col>
      </Row>
    </Card>
  )
}
